<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
// import { VbenIcon } from '@vben/icons';
import { getPopupContainer } from '@vben/utils';

import { FilterOutlined, RedoOutlined } from '@ant-design/icons-vue';
import {
  Empty,
  InputSearch,
  message,
  Popover,
  Skeleton,
  Spin,
  // Tag,
  Tooltip,
} from 'ant-design-vue';
import { debounce } from 'lodash-es';

import { useVbenForm } from '#/adapter/form';
import { employeePage } from '#/api/company/audience';
import { companyInfo } from '#/api/company/manage';
import { groupInfo } from '#/api/register/group';
import { registerPage } from '#/api/register/personal';
import { bottomOffset } from '#/views/workflow/task/constant';

import AudienceCard from './components/audience-card.vue';
import ContactPanel from './components/contact-panel.vue';
import { querySchema } from './workbench';

const emptyImage = Empty.PRESENTED_IMAGE_SIMPLE;

const route = useRoute();
const tableList = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const loading = ref(false);
const searchName = ref<string>();
const popoverOpen = ref(false);
const formData = ref<Record<string, any>>({});

const [SearchForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 100,
    componentProps: {
      allowClear: true,
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: querySchema(),
  handleSubmit: async (values: Record<string, any>) => {
    console.log('values', values);
    searchName.value = undefined;
    formData.value = { ...values };
    await reload(false);
  },
  handleReset: async () => {
    formData.value = {};
    await formApi.resetForm();
    formApi.setLatestSubmissionValues(formApi.form.values);
    await reload(true);
  },
  wrapperClass: 'w-[350px]',
});

/**
 * 是否已经加载全部数据 即 tableList.length === total
 */
const isLoadComplete = computed(() => tableList.value.length === total.value);
const lastSelectId = ref<number | string>();
const currentCard = ref<any>();

// 卡片父容器的ref
const cardContainerRef = useTemplateRef('cardContainerRef');

/**
 * @param resetFields 是否清空查询参数
 */
async function reload(resetFields: boolean = false) {
  // 需要先滚动到顶部
  cardContainerRef.value?.scroll({ top: 0, behavior: 'auto' });

  page.value = 1;
  currentCard.value = undefined;
  total.value = 0;
  lastSelectId.value = '';

  if (resetFields) {
    searchName.value = undefined;
    formData.value = {};
  }

  const pageQuery = {
    pageSize: 10,
    pageNum: page.value,
  };

  const postData: Record<string, any> = {
    name: searchName.value,
    ...formData.value,
  };

  const pageApiMap: Record<string, any> = {
    company: () => {
      return employeePage({ ...pageQuery, ...postData });
    },
    group: () => {
      return registerPage(pageQuery, postData);
    },
  };

  const type = route.query.type as string;
  const pageApi = pageApiMap[type];

  if (type === 'company') {
    postData.companyId = route.query.companyId;
  }
  if (type === 'group') {
    postData.groupId = route.query.groupId;
  }

  loading.value = true;
  const resp = await pageApi();
  tableList.value = resp.rows.map((item: any) => {
    if (type === 'group') {
      item.id = item.employeeId;
    }
    return { ...item, active: false };
  });
  total.value = resp.total;

  loading.value = false;
  // 默认选中第一个
  if (tableList.value.length > 0) {
    const firstCard = tableList.value[0]!;
    currentCard.value = firstCard;
    handleCardClick(firstCard);
  }
}

const handleScroll = debounce(async (e: Event) => {
  if (!e.target) {
    return;
  }
  // e.target.scrollTop 是元素顶部到当前可视区域顶部的距离，即已滚动的高度。
  // e.target.clientHeight 是元素的可视高度。
  // e.target.scrollHeight 是元素的总高度。
  const { scrollTop, clientHeight, scrollHeight } = e.target as HTMLElement;
  // 判断是否滚动到底部
  const isBottom = scrollTop + clientHeight >= scrollHeight - bottomOffset;

  // 滚动到底部且没有加载完成
  if (isBottom && !isLoadComplete.value) {
    loading.value = true;
    page.value += 1;
    const resp = await employeePage({
      pageSize: 10,
      pageNum: page.value,
      ...formData.value,
    });
    tableList.value.push(
      ...resp.rows.map((item) => ({ ...item, active: false })),
    );
    loading.value = false;
  }
}, 200);

const isCalling = ref(false);

async function handleCardClick(item: any) {
  const { id } = item;
  // 点击的是同一个
  if (lastSelectId.value === id) {
    return;
  }
  if (isCalling.value) {
    // 当前通话中，无法切换其他人
    message.warning('当前通话中，无法切换其他人员');
    return;
  }
  currentCard.value = item;
  // 反选状态 & 如果已经点击了 不变 & 保持只能有一个选中
  tableList.value.forEach((item) => {
    item.active = item.id === id;
  });
  lastSelectId.value = id;
  console.log(item);
}

const infoLoading = ref(false);
const cuffInfo = ref<any>();
const { setTabTitle } = useTabs();
onMounted(async () => {
  formApi.updateSchema([
    {
      fieldName: 'labelIds',
      componentProps: {
        onClose: () => {
          // 由于失去焦点浮层会消失 使用v-model选择标签完毕后强制显示
          popoverOpen.value = true;
        },
      },
    },
  ]);

  const type = route.query.type as string;
  infoLoading.value = true;
  if (type === 'company') {
    const companyDetails = await companyInfo(route.query.companyId as string);
    if (companyDetails) {
      infoLoading.value = false;
      cuffInfo.value = companyDetails;
      setTabTitle(`${companyDetails.name} - 企业呼叫工作台`);
    } else {
      message.warning('查无此企业');
    }
  }

  if (type === 'group') {
    const groupDetails = await groupInfo(route.query.groupId as string);
    if (groupDetails) {
      infoLoading.value = false;
      cuffInfo.value = groupDetails;
      setTabTitle(
        `${groupDetails.name} - ${groupDetails.number}届参观团呼叫工作台`,
      );
    } else {
      message.warning('查无此参观团');
    }
  }

  await reload();
});
</script>

<template>
  <Page :auto-content-height="true">
    <Skeleton v-if="infoLoading" active />
    <div v-else class="flex h-full gap-2">
      <div
        class="bg-background relative flex h-full min-w-[330px] max-w-[360px] flex-col rounded-lg"
      >
        <!-- 搜索条件 -->
        <div
          class="bg-background z-100 sticky left-0 top-0 flex w-full items-center gap-1 rounded-t-lg border-b-[1px] border-solid p-2"
        >
          <div class="flex-1">
            <InputSearch
              v-model:value="searchName"
              placeholder="输入名称搜索"
              @search="reload(false)"
            />
          </div>
          <div class="flex items-center gap-1">
            <Tooltip placement="top" title="刷新">
              <a-button @click="reload(true)">
                <RedoOutlined />
              </a-button>
            </Tooltip>
            <Popover
              v-model:open="popoverOpen"
              :get-popup-container="getPopupContainer"
              placement="rightTop"
              trigger="click"
            >
              <template #title>
                <div class="w-full border-b pb-[12px] text-[16px]">搜索</div>
              </template>
              <template #content>
                <SearchForm />
              </template>
              <a-button>
                <FilterOutlined />
              </a-button>
            </Popover>
          </div>
        </div>
        <div
          ref="cardContainerRef"
          class="thin-scrollbar flex flex-1 flex-col gap-2 overflow-y-auto py-3 pr-3"
          @scroll="handleScroll"
        >
          <template v-if="tableList.length > 0">
            <div
              v-for="item in tableList"
              :key="item.id"
              class="mb-3 flex items-center gap-2 px-2"
            >
              <AudienceCard :info="item" @click="handleCardClick(item)" />
            </div>
          </template>
          <Empty v-else :image="emptyImage" />
          <div
            v-if="isLoadComplete && tableList.length > 0"
            class="flex items-center justify-center text-[14px] opacity-50"
          >
            没有更多数据了
          </div>
          <!-- 遮罩loading层 -->
          <div
            v-if="loading"
            class="absolute left-0 top-0 flex h-full w-full items-center justify-center bg-[rgba(0,0,0,0.1)]"
          >
            <Spin tip="加载中..." />
          </div>
        </div>
        <!-- total显示 -->
        <div
          class="bg-background sticky bottom-0 w-full rounded-b-lg border-t-[1px] py-2"
        >
          <div class="flex items-center justify-center">
            共 {{ total }} 条记录
          </div>
        </div>
      </div>

      <!-- 联络面板 -->
      <ContactPanel
        v-model:calling="isCalling"
        :audience="currentCard"
        type="list"
      />
    </div>
  </Page>
</template>

<style scoped lang="scss"></style>
